﻿using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB;
using MongoDB.Linq;

namespace MongoDBDemo
{
    //这里可以用泛型类的,到时候再优化下
    public class MongoDBOpration
    {

    //    private static readonly string connection = "Server=127.0.0.1";
    //    private static readonly string dbName = "MyNorthwind";

    //    public void Insert(Customer customer)
    //    {
    //        using(Mongo mongo = new Mongo(connection))
    //        {
    //            mongo.Connect();
    //            var db = mongo.GetDatabase(dbName);
    //            var collection = db.GetCollection<Customer>();
    //            collection.Insert(customer);
    //            //// 根据类型获取相应的集合
    //            //var collection = db.GetCollection<Customer>();
    //            //// 向集合中插入对象
    //            //collection.Insert(customer);
    //        }

    //    }

    //    public void Delete(string customerId)
    //    {
    //        using(Mongo mongo = new Mongo(connection))
    //        {
    //            mongo.Connect();
    //            var db = mongo.GetDatabase(dbName);
    //            var collection = db.GetCollection<Customer>();
    //            connection.Remove(x => x.CustomerId == customerId);
    //        }
    //    }

    //    public void Update(Customer customer)
    //    {
    //        using(Mongo mongo = new Mongo(connection))
    //        {
    //            mongo.Connect();
    //            var db = mongo.GetDatabase(dbName);
    //            var collection = db.GetCollection<Customer>();
    //            // 更新对象
    //            collection.Update(customer, (x => x.CustomerId == customer.CustomerId));
    //        }
    //    }

    //    public List<Customer> GetList(string searchWord, PagingInfo pagingInfo)
    //    {
    //        using (Mongo mongo = new Mongo(connection))
    //        {
    //            mongo.Connect();
    //            var db = mongo.GetDatabase(dbName);
    //            var collection = db.GetCollection<Customer>();

    //            // 先创建一个查询
    //            var query = from customer in collection.Linq()
    //                        select customer;
                
                
    //            // 增加查询过滤条件
    //            if (string.IsNullOrEmpty(searchWord) == false)
    //                query = query.Where(c => c.CustomerName.Contains(searchWord) || c.Address.Contains(searchWord));

    //            // 先按名称排序，再返回分页结果.
    //            return query.OrderBy(x => x.CustomerName).GetPagingList<Customer>(pagingInfo);
    //        }
    //    }


        public static void Insert(Customer customer)
        {
            customer.CustomerId = Guid.NewGuid().ToString("N");

            using (MyMongoDb mm = new MyMongoDb())
            {
                mm.GetCollection<Customer>().Insert(customer);
            }
        }
    }

}
